import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY } from '../decorators/roles.decorator';

@Injectable()
export class RolesGuard implements CanActivate {
    constructor(private reflector: Reflector) { }

    canActivate(context: ExecutionContext): boolean {
        const requiredRoles = this.reflector.getAllAndOverride<string[]>(ROLES_KEY, [
            context.getHandler(),
            context.getClass(),
        ]);
        if (!requiredRoles) {
            return true;
        }
        const { user } = context.switchToHttp().getRequest();

        // 确保用户存在且有角色属性
        if (!user || !user.roles) {
            throw new ForbiddenException('无法验证用户权限');
        }

        const hasRole = () => requiredRoles.some((role) => user.roles.includes(role));

        if (!hasRole()) {
            throw new ForbiddenException('您没有权限执行此操作');
        }

        return true;
    }
} 